<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      
      <el-form-item label="省" prop="provinceId">
        <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
           <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="cityId">
        <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
           <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区/县" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择区/县" clearable>
           <el-option
                v-for="item in areaData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据状态" prop="isAdopt">
        <el-select v-model="queryParams.isAdopt" placeholder="请选择">
          <el-option v-for="item in [{ value: '0', label: '待采纳' }, { value: '1', label: '已采纳' }, { value: '2', label: '已入库' }]" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属任务" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入所属任务"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交人" prop="submitter">
        <el-input
          v-model="queryParams.submitter"
          placeholder="请输入提交人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="提交时间" style="width: 330px">
        <el-date-picker
           v-model="submitTime"
           value-format="YYYY-MM-DD"
           type="daterange"
           range-separator="-"
           start-placeholder="开始日期"
           end-placeholder="结束日期"
        ></el-date-picker>
			</el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:difference:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:difference:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain icon="Download" @click="handleImport">导入</el-button>
    	</el-col>
    	<el-col :span="1.5">
	      <el-button plain icon="Edit"  @click="handleExport">导出</el-button>
	    </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:difference:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" stripe :data="differenceList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      <el-table-column label="区/县" align="center" prop="area" />
      <el-table-column label="所属任务" align="center" prop="taskName" />
      <el-table-column label="数据状态" align="center" prop="isAdopt">
      	<template #default="scope">
          <span v-if="scope.row.isAdopt=='0'">待采纳</span>
          <span v-if="scope.row.isAdopt=='1'">已采纳</span>
          <span v-if="scope.row.isAdopt=='2'">已入库</span>
        </template>
      </el-table-column>
      <el-table-column label="提交人姓名" align="center" prop="submitter" />
      <el-table-column label="提交时间" align="center" prop="submitTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
						v-if="scope.row.taskStatus!=2 && scope.row.flag==2"
          >修改</el-button>
          <el-button
            type="text"
            @click="handleView(scope.row)"
		        v-if="scope.row.flag==1 || scope.row.flag==2"    
          >查看</el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
						v-if="scope.row.taskStatus!=2 && scope.row.flag==2"
          >删除</el-button>
          <el-button
            type="text"
            @click="handleAdopt(scope.row)"
						v-if="scope.row.isAdopt=='0'"
          >采纳</el-button>
          <el-button
            type="text"
            @click="handleUnAdopt(scope.row)"
						v-if="scope.row.isAdopt=='1'"
          >取消采纳</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.rows"
      @pagination="getList"
    />

    <!-- 添加或修改区县致死性差异性对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="differenceRef" :model="form" :rules="rules" label-width="120px">
      	<p class="dialogTitle">{{title}}</p>
       <el-row>
  			<el-col :span="12">
	        <el-form-item label="省" prop="provinceId">
	          <el-select v-model="form.provinceId" placeholder="请输入省" @change="chooseFormProvince" :disabled="isEdit" style="width: 100%;">
           		<el-option
                v-for="item in provinceFormData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            	</el-option>
        		</el-select>
	        </el-form-item>
	    	</el-col>
	       <el-col :span="12">
	        <el-form-item label="市" prop="cityId">
	          <el-select v-model="form.cityId" placeholder="请输入市" @change="chooseFormCity" :disabled="isEdit" style="width: 100%;">
           		<el-option
                v-for="item in cityFormData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            	</el-option>
        		</el-select>
	        </el-form-item>
	    	</el-col>
       	</el-row>
       	<el-row>
	  			<el-col :span="12">
		        <el-form-item label="区/县" prop="areaId">
		          <el-select v-model="form.areaId" placeholder="请输入区/县" :disabled="isEdit" style="width: 100%;">
	               <el-option
		                v-for="item in areaFormData"
		                :key="item.id"
		                :label="item.name"
		                :value="item.id">
	                </el-option>
	            </el-select>
		        </el-form-item>
	       </el-col>
	        <el-col :span="12">
		        <el-form-item label="所属任务" prop="taskName">
		          <el-select v-model="form.taskName" placeholder="请输入所属任务" filterable :disabled="isEdit" @change="chooseTaskName" style="width: 100%;">
	               <el-option
		                v-for="(item,index) in taskNameData"
		                :key="item.taskNum"
		                :label="item.taskCodeAndTaskName"
		                :value="item.taskName">
	                </el-option>
	            </el-select>
		        </el-form-item>
	        </el-col>	       	
   			</el-row>  			
   			<el-row>
   				<el-col :span="12">
	       		<el-form-item label="提交人" prop="submitter">
		          <el-input v-model="form.submitter" disabled placeholder="请输入提交人" />
		        </el-form-item>
	       	</el-col>
	       	<el-col :span="12">
		       	<el-form-item label="提交时间" prop="submitTime">
		          <el-date-picker clearable
		            v-model="form.submitTime"
		            type="date"
		            style="width: 100%;"
		            disabled
		            value-format="YYYY-MM-DD"
		            placeholder="请选择提交时间">
		          </el-date-picker>
		        </el-form-item>
        	</el-col>
   			</el-row>
   			<el-row>
   				<el-col :span="12">
		        <el-form-item label="指标名称">
              <el-input type="hidden" />
		          <span>建筑物</span>
		        </el-form-item>
		      </el-col>
	  			<el-col :span="12">
		        <el-form-item label="建筑物指标值" prop="building">
		          <el-input v-model="form.building" placeholder="请输入建筑物指标值" />
		        </el-form-item>
		      </el-col>
   			</el-row>
        <el-form-item label="建筑物说明" prop="buildingExplain">
          <el-input v-model="form.buildingExplain" type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}" placeholder="请输入建筑物说明" />
        </el-form-item>
        <el-form-item label="建筑物附件" prop="buildingFile">
          <el-input type="hidden" />
          <file-upload ref="fileBuilding" :disabled="isEditFile" v-model="form.buildingFile"/>
        </el-form-item>
        <el-row>
   				<el-col :span="12">
		        <el-form-item label="指标名称">
              <el-input type="hidden" />
		          <span>人口</span>
		        </el-form-item>
		      </el-col>
	  			<el-col :span="12">
		        <el-form-item label="人口指标值" prop="peopleNum">
		          <el-input v-model="form.peopleNum" placeholder="请输入人口指标值" />
		        </el-form-item>
		      </el-col>
   			</el-row>
        <el-form-item label="人口说明" prop="peopleNumExplain">
          <el-input v-model="form.peopleNumExplain" type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}" placeholder="请输入人口说明" />
        </el-form-item>
        <el-form-item label="人口附件" prop="peopleNumFile">
          <el-input type="hidden" />
          <file-upload ref="filePeopleNum" :disabled="isEditFile" v-model="form.peopleNumFile"/>
        </el-form-item>
        <el-row>
   				<el-col :span="12">
		        <el-form-item label="指标名称">
              <el-input type="hidden" />
		          <span>地形地貌</span>
		        </el-form-item>
		      </el-col>
	  			<el-col :span="12">
	  				<el-form-item label="地形地貌指标值" prop="terrain">
		          <el-input v-model="form.terrain" placeholder="请输入地形地貌指标值" />
		        </el-form-item>
	  			</el-col>
   			</el-row>
        <el-form-item label="地形地貌说明" prop="terrainExplain">
          <el-input v-model="form.terrainExplain"  type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}" placeholder="请输入地形地貌说明" />
        </el-form-item>
        <el-form-item label="地形地貌附件" prop="terrainFile">
          <el-input type="hidden" />
          <file-upload ref="fileTerrain" :disabled="isEditFile" v-model="form.terrainFile"/>
        </el-form-item>
        <el-row>
   				<el-col :span="12">
		        <el-form-item label="指标名称">
              <el-input type="hidden" />
		          <span>道路交通</span>
		        </el-form-item>
		      </el-col>
	  			<el-col :span="12">
	  				<el-form-item label="道路交通指标值" prop="traffic">
		          <el-input v-model="form.traffic" placeholder="请输入道路交通指标值" />
		        </el-form-item>
	  			</el-col>
   			</el-row>       
        <el-form-item label="道路交通说明" prop="trafficExplain">
          <el-input v-model="form.trafficExplain" type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}" placeholder="请输入道路交通说明" />
        </el-form-item>
        <el-form-item label="道路交通附件" prop="trafficFile">
          <el-input type="hidden" />
          <file-upload ref="fileTraffic" :disabled="isEditFile" v-model="form.trafficFile"/>
        </el-form-item>
        <el-row>
   				<el-col :span="12">
		        <el-form-item label="指标名称">
              <el-input type="hidden" />
		          <span>气候</span>
		        </el-form-item>
		      </el-col>
	  			<el-col :span="12">
	  				<el-form-item label="气候指标值" prop="climate">
		          <el-input v-model="form.climate" placeholder="请输入气候指标值" />
		        </el-form-item>
	  			</el-col>
   			</el-row>
        <el-form-item label="气候说明" prop="climateExplain">
          <el-input v-model="form.climateExplain" type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}"  placeholder="请输入气候说明" />
        </el-form-item>
        <el-form-item label="气候附件" prop="climateFile">
          <el-input type="hidden" />
          <file-upload ref="fileClimate" :disabled="isEditFile" v-model="form.climateFile"/>
        </el-form-item>
        <el-row class="mb20">
   				<el-col :span="24" style="text-align: center;">
		        <el-button type="primary" icon="Plus" @click="addCustom">添加自定义指标</el-button>
		     </el-col>
   			</el-row>
        <el-row v-for="(item,index) in form.customIndicatorList" :key="item.index">
   				<el-col :span="12">
   					<el-form-item label="自定义指标名称" :prop="`customIndicatorList.` + index + '.customIndicatorName'">
		          <el-input v-model="item.customIndicatorName" placeholder="请输入自定义指标名称" />
		        </el-form-item>
   				</el-col>
   				<el-col :span="12">
   					<el-form-item label="自定义指标值" :prop="`customIndicatorList.` + index + '.customIndicatorValue'">
		          <el-input v-model="item.customIndicatorValue" placeholder="请输入自定义指标值" />
		        </el-form-item>
   				</el-col>
   				<el-col :span="24">
	   				<el-form-item label="自定义说明" :prop="`customIndicatorList.` + index + '.customIndicatorExplain'">
		          <el-input v-model="item.customIndicatorExplain"  type="textarea" maxlength="200" show-word-limit :autosize="{ minRows: 4, maxRows: 5}" placeholder="请输入自定义说明" />
		        </el-form-item>
	        </el-col>
	        <el-col :span="24">
		        <el-form-item label="自定义附件" :prop="`customIndicatorList.` + index + '.customIndicatorFile'">
		          <file-upload ref="customFile" :disabled="isEditFile" v-model="item.customIndicatorFile"/>
		        </el-form-item>
	        </el-col>
	        <el-col :span="4" :offset="20" style="margin-bottom: 30px;">
        		<el-button type="primary" @click="delCustomIndicator(index,item)">删除</el-button>
        	</el-col>
   			</el-row>
   
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="isSave" v-show="isShow">保 存</el-button>
          <el-button plain @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <p></p>
       <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :before-upload="handleFileBeforeUpload"
          :on-progress="handleFileUploadProgress"
          :on-error="handleFileUploadError"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
       >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
             <div class="el-upload__tip text-center">
                <span>仅允许导入xls格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('区县致死性差异性模板.xls')">下载模板</el-link>
             </div>
          </template>
       </el-upload>
       <template #footer>
          <div class="dialog-footer">
             <el-button type="primary" @click="submitFileForm">确 定</el-button>
             <el-button plain @click="upload.open = false">取 消</el-button>
          </div>
       </template>
    </el-dialog>
  </div>
</template>

<script setup name="Difference">
import { listDifference, getDifference, delDifference, adoptDifference, addDifference, updateDifference, getTask, delCustom } from "@/api/basedatamanage/difference";
import { getProvince, getChildArea} from "@/api/system/division";
import { getUserId, setUserId } from '@/utils/auth'
import { isDecimal } from '@/utils/validate'
import { getToken } from "@/utils/auth";
import useUserStore from '@/store/modules/user'

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

/*** 导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "token " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/lethalityDifference/uploadLethalityDifference"
});
const differenceList = ref([]);
const isEdit = ref(false);
const isEditFile = ref(false);
const isShow = ref(true);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const submitTime = ref("");//提交时间
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const taskNameData = ref([]);
const isShowCustom1 = ref(false);
const isShowCustom2 = ref(false);
const isShowCustom3 = ref(false);
const isShowCustom4 = ref(false);
const isShowCustom5 = ref(false);
const clickNum = ref(0);

const data = reactive({
  form: {
  	customIndicatorList:[{
  		customIndicatorName:null,
  		customIndicatorValue:null,
  		customIndicatorExplain:null,
  		customIndicatorFile:null
  	}]
  },
  queryParams: {
    page: 1,
    rows: 10,
    taskName: null,
    provinceId: null,
    cityId: null,
    areaId: null,
    submitter: null,
    submitTime: null,
    startTime:null,
    endTime:null,
  },
  rules: {
    taskCode: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省不能为空", trigger: "blur" }
    ],
    provinceId: [
      { required: true, message: "省不能为空", trigger: "blur" }
    ],
    city: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    cityId: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    area: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "区/县 不能为空", trigger: "blur" }
    ],
    building: [
      { required: true,  trigger: "blur", validator: isDecimal }
    ],
    buildingExplain: [
      { required: true, message: "建筑物说明不能为空", trigger: "blur" }
    ],
    peopleNum: [
      { required: true,  trigger: "blur", validator: isDecimal }
    ],
    peopleNumExplain: [
      { required: true, message: "人口说明不能为空", trigger: "blur" }
    ],
    terrain: [
      { required: true,  trigger: "blur", validator: isDecimal  }
    ],
    terrainExplain: [
      { required: true, message: "地形地貌说明不能为空", trigger: "blur" }
    ],
    traffic: [
      { required: true, trigger: "blur", validator: isDecimal }
    ],
    trafficExplain: [
      { required: true, message: "道路交通说明不能为空", trigger: "blur" }
    ],
    climate: [
      { required: true,  trigger: "blur", validator: isDecimal  }
    ],
    climateExplain: [
      { required: true, message: "气候说明不能为空", trigger: "blur" }
    ],
    createName: [
      { required: true, message: "创建人姓名不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询区县致死性差异性列表 */
function getList() {
  loading.value = true;
  listDifference(queryParams.value).then(response => {
    differenceList.value = response.data.rows;;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
	    provinceData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
	getTask().then(response => {
	    taskNameData.value = response.data;
	});
}

function editProvinceFormData(provinceId,cityId) {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
	getChildArea(provinceId).then(response => {
    cityFormData.value = response.data;
	});
	getChildArea(cityId).then(response => {
	    areaFormData.value = response.data;
	});
}

function chooseProvince(value){
	queryParams.value.cityId = null;
	queryParams.value.areaId = null;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value).then(response => {
    cityData.value = response.data;
	});
//	provinceData.value.map(item => {//遍历数据
//		if(item.id == value){
//			if(item.name == "北京市"||item.name == "天津市"||item.name == "上海市"||item.name == "重庆市"){
//		    cityData.value.push(JSON.parse(JSON.stringify(item)));
//			}else{
//				getChildArea(value).then(response => {
//			    cityData.value = response.data;
//				});
//			}
//			return;
//		}   
//})		
}

function chooseFormProvince(value){
	form.value.city = null;
	form.value.area = null;
	cityFormData.value = [];
	areaFormData.value = [];
	getChildArea(value).then(response => {
    cityFormData.value = response.data;
	});	
}

function chooseCity(value){
	queryParams.value.areaId = null;
	areaData.value = [];
	getChildArea(value).then(response => {
	    areaData.value = response.data;
	});
}

function chooseFormCity(value){
	form.value.area = null;
	areaFormData.value = [];
	getChildArea(value).then(response => {
	    areaFormData.value = response.data;
	});
}
function chooseTaskName(value){
	taskNameData.value.map(item => {//遍历数据
		if(item.taskName == value){
			form.value.taskCode = item.taskNum;
			console.log(form.value.taskCode)
			return;
		}   
	})	

}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    taskCode: null,
    taskName: null,
    province: null,
    provinceId: null,
    city: null,
    cityId: null,
    area: null,
    areaId: null,
    building: null,
    buildingExplain: null,
    buildingFile: null,
    peopleNum: null,
    peopleNumExplain: null,
    peopleNumFile: null,
    terrain: null,
    terrainExplain: null,
    terrainFile: null,
    traffic: null,
    trafficExplain: null,
    trafficFile: null,
    climate: null,
    climateExplain: null,
    climateFile: null,
    customIndicatorList:[],
//  customIndicatorName1: null,
//  customIndicatorValue1: null,
//  customIndicatorExplain1: null,
//  customIndicatorFile1: null,
//  customIndicatorName2: null,
//  customIndicatorValue2: null,
//  customIndicatorExplain2: null,
//  customIndicatorFile2: null,
//  customIndicatorName3: null,
//  customIndicatorValue3: null,
//  customIndicatorExplain3: null,
//  customIndicatorFile3: null,
//  customIndicatorName4: null,
//  customIndicatorValue4: null,
//  customIndicatorExplain4: null,
//  customIndicatorFile4: null,
//  customIndicatorName5: null,
//  customIndicatorValue5: null,
//  customIndicatorExplain5: null,
//  customIndicatorFile5: null,
    isSubmit: null,
    delFlag: null,
    createName: null,
    createId: null,
    createTime: null,
    submitter: null,
    submitterId: null,
    submitTime: null
  };
  proxy.resetForm("differenceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  queryParams.value.startTime = submitTime.value? submitTime.value[0] : "";
  queryParams.value.endTime = submitTime.value? submitTime.value[1] : "";
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
	submitTime.value = [];
	cityData.value = [];
	areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//获取当前日期函数
function getNowFormatDate() {
  let date = new Date(),
    seperator1 = '-', //格式分隔符
    year = date.getFullYear(), //获取完整的年份(4位)
    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
    strDate = date.getDate() // 获取当前日(1-31)
  if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
  if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0
 
  let currentdate = year + seperator1 + month + seperator1 + strDate 
  return currentdate
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isShow.value = true;
  isEdit.value = false;
  isEditFile.value = false;
  clickNum.value = 0;
  form.value.submitter = userStore.name;
  form.value.submitterId = getUserId();
  form.value.createId = getUserId();
  form.value.createName = userStore.name;
  form.value.submitTime = getNowFormatDate();
  getProvinceFormData();  
  open.value = true;
  title.value = "添加区县致死性差异性";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  isShow.value = true;
  isEdit.value = true;
  isEditFile.value = false;
  clickNum.value = 0;
  getDifference(id).then(response => {
  	editProvinceFormData(response.data.data.provinceId,response.data.data.cityId)
    form.value = response.data.data;
    form.value.buildingFile = response.data.buildingFile;
    form.value.peopleNumFile = response.data.peopleNumFile;
    form.value.terrainFile = response.data.terrainFile;    
    form.value.trafficFile = response.data.trafficFile;
    form.value.climateFile = response.data.climateFile;

    form.value.customIndicatorList.forEach((item,index) => {//遍历数据
			if(item.customFileList!=[]){
				item.customIndicatorFile = item.customFileList;
			}else{
				item.customIndicatorFile = null
			}
			
		})
		open.value = true;
    title.value = "修改区县致死性差异性";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  reset();
  const id = row.id || ids.value
  isShow.value = false;
  isEdit.value = true;
  isEditFile.value = true;
  isShowCustom1.value = false;
  isShowCustom2.value = false;
  isShowCustom3.value = false;
  isShowCustom4.value = false;
  isShowCustom5.value = false;
  clickNum.value = 0;
  getDifference(id).then(response => {
  	editProvinceFormData(response.data.data.provinceId,response.data.data.cityId)
    form.value = response.data.data;
    form.value.buildingFile = response.data.buildingFile;
    form.value.peopleNumFile = response.data.peopleNumFile;
    form.value.terrainFile = response.data.terrainFile;    
    form.value.trafficFile = response.data.trafficFile;
    form.value.climateFile = response.data.climateFile;
    
    form.value.customIndicatorList.forEach((item,index) => {//遍历数据		
			if(item.customFileList!=[]){
				item.customIndicatorFile = item.customFileList;
			}else{
				item.customIndicatorFile = null
			}
		})
    
    
    open.value = true;
    title.value = "查看区县致死性差异性";
  });
}

/** 提交按钮 */
const isSave = ref(false);
function submitForm() {
	console.log(proxy.$refs["fileBuilding"].fileList)
	console.log(proxy.$refs["filePeopleNum"].fileList)
	console.log(proxy.$refs["fileTerrain"].fileList)
	console.log(proxy.$refs["fileTraffic"].fileList)
	console.log(proxy.$refs["fileClimate"].fileList)
	console.log(form.value.taskCode)
	
	const fileBuildingList = JSON.parse(JSON.stringify(proxy.$refs["fileBuilding"].fileList));
	const filePeopleNumList = JSON.parse(JSON.stringify(proxy.$refs["filePeopleNum"].fileList));
	const fileTerrainList = JSON.parse(JSON.stringify(proxy.$refs["fileTerrain"].fileList));
	const fileTrafficList = JSON.parse(JSON.stringify(proxy.$refs["fileTraffic"].fileList));
	const fileClimateList = JSON.parse(JSON.stringify(proxy.$refs["fileClimate"].fileList));
	
	

	
  const fileBuildingIds = [];
  const filePeopleNumIds = [];
  const fileTerrainIds = [];
  const fileTrafficIds = [];
  const fileClimateIds = [];
  
  
  const fileCustomFile2Ids = [];
  const fileCustomFile3Ids = [];
  const fileCustomFile4Ids = [];
  const fileCustomFile5Ids = [];
  
  for(var i = 0; i<fileBuildingList.length;i++) {
	   fileBuildingIds.push(fileBuildingList[i].attachId)
 	}
  for(var i = 0; i<filePeopleNumList.length;i++) {
	   filePeopleNumIds.push(filePeopleNumList[i].attachId)
 	}
  for(var i = 0; i<fileTerrainList.length;i++) {
	   fileTerrainIds.push(fileTerrainList[i].attachId)
 	}
  for(var i = 0; i<fileTrafficList.length;i++) {
	   fileTrafficIds.push(fileTrafficList[i].attachId)
 	}
  for(var i = 0; i<fileClimateList.length;i++) {
	   fileClimateIds.push(fileClimateList[i].attachId)
 	}

  
	form.value.customIndicatorList.forEach((item,index) => {//遍历数据
		const customFile1List = JSON.parse(JSON.stringify(proxy.$refs.customFile[index].fileList));
		//console.log(customFile1List)
		const fileCustomFile1Ids = [];
		for(var i = 0; i<customFile1List.length;i++) {
	   	fileCustomFile1Ids.push(customFile1List[i].attachId)
	   	item.customIndicatorFile = fileCustomFile1Ids.join(",");
   	}
		
	})
  
  form.value.buildingFile = fileBuildingIds.join(",");
  form.value.peopleNumFile = filePeopleNumIds.join(",");
  form.value.terrainFile = fileTerrainIds.join(",");
  form.value.trafficFile = fileTrafficIds.join(",");
  form.value.climateFile = fileClimateIds.join(",");
  
  
  proxy.$refs["differenceRef"].validate(valid => {
    if (valid) {
      isSave.value = true;
      if (form.value.id != null) {
      	form.value.customIndicatorList.forEach((item,index) => {//遍历数据					
				  delete item.customFileList
				})
        updateDifference(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          isSave.value = false;
          getList();
        }).catch(err=>{isSave.value = false});
      } else {
        addDifference(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          isSave.value = false;
          getList();
        }).catch(err=>{isSave.value = false});
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除"' + row.province +'' + row.city +'' + row.area +'"的数据项？').then(function() {
    return delDifference(ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 采纳按钮操作 */
function handleAdopt(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认采纳"' + row.province +'' + row.city +'' + row.area +'"的数据项？').then(function() {
    //return adoptDifference(ids,"1");
    return  adoptDifference(ids,"1").then(response => {
    	console.log(response.message)
    	if(response.message=="一个区县只能指定一组被采纳的指标值，如需变更，请先取消采纳本任务相同区县的数据。"){
    		
    		proxy.$modal.msgWarning(response.message);
    	}else{
        console.log('22222');
    		proxy.$modal.msgSuccess(response.message);
    	}
           
    });
  }).then(() => {
    getList();
    //proxy.$modal.msgSuccess("采纳成功");
  }).catch(() => {});
}

/** 取消采纳按钮操作 */
function handleUnAdopt(row) {
  const ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认取消采纳"' + row.province +'' + row.city +'' + row.area +'"的数据项？').then(function() {
    adoptDifference(ids,"0").then(response => {
    	if(response.message=="一个区县只能指定一组被采纳的指标值，如需变更，请先取消采纳本任务相同区县的数据。"){
    		proxy.$modal.msgWarning(response.message);
    	}else{
    		proxy.$modal.msgSuccess(response.message);
    	}
           
    });
  }).then(() => {
    getList();
    //proxy.$modal.msgSuccess("取消采纳成功");
  }).catch(() => {});
}


// 模板下载
function importTemplate(name) {
  proxy.download("/base/product/downloadExcel", {
    fileName:name
  }, name);
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    upload.open = true;
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在上传文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/lethalityDifference/exportLethalityDifference', {
    ...queryParams.value
  }, `区县致死性差异性_${new Date().getTime()}.xls`)
}

/** 添加自定义指令按钮操作 */
function addCustom() {
	//clickNum.value = clickNum.value + 1
	console.log(form.value.customIndicatorList.length)
//if(clickNum.value == 1){
//	isShowCustom1.value = true 
//}else if(clickNum.value == 2){
//	isShowCustom2.value = true
//}else if(clickNum.value == 3){
//	isShowCustom3.value = true
//}else if(clickNum.value == 4){
//	isShowCustom4.value = true
//}else if(clickNum.value == 5){
//	isShowCustom5.value = true
//}
	if(form.value.customIndicatorList.length < 5){
		form.value.customIndicatorList.push({
			customIndicatorName:null,
  		customIndicatorValue:null,
  		customIndicatorExplain:null,
  		customIndicatorFile:null
		})
	}
//	if(clickNum.value > 5){
//		clickNum.value = 4;
//	}
	
}
function delCustomIndicator(index,item){
	
	if (item.id != null) {
		proxy.$modal.confirm('是否确认删除？').then(function() {
	    return delCustom(item.id);
	  }).then(() => {
	    form.value.customIndicatorList.splice(index, 1);
	    proxy.$modal.msgSuccess("删除成功");
	  }).catch(() => {});
    
  } else {
    form.value.customIndicatorList.splice(index, 1);
  }
}

getList();
getProvinceData();
</script>
